package com.zzy.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzy.domain.dto.GoodsDto;
import com.zzy.domain.po.SKU;
import com.zzy.domain.po.SPU;
import com.zzy.domain.vo.GoodsVo;
import com.zzy.domain.vo.PageResult;
import com.zzy.mapper.GoodsMapper;
import com.zzy.service.GoodsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * spu
 * @author YXL
 */
@Service
@RequiredArgsConstructor
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, SPU> implements GoodsService {
    private final GoodsMapper goodsMapper;

    @Override
    public Boolean addGoods(SPU spu) {
        if (CollUtil.isEmpty(spu.getSkuList())){
            //为空则给一个空集合
            spu.setSkuList(new ArrayList<>());
        }
        List<SKU> skus = spu.getSkuList();
        //保存spu
        Boolean b = save(spu);
        //批量保存sku
        if (b && spu.getId() != null) {
            Long spuId = spu.getId();
            skus.forEach(sku -> {
                sku.setCreateTime(LocalDateTime.now());
                sku.setSpuId(spuId);
                sku.setIsDel(1); // 设置未删除状态
                // 添加空值检查，避免 NullPointerException
                if (sku.getProductHeight() != null && sku.getProductLength() != null && sku.getProductWidth() != null) {
                    sku.setProductVolume(sku.getProductHeight() * sku.getProductLength() * sku.getProductWidth());
                } else {
                    sku.setProductVolume(0); // 如果任一维度为null，则将体积设为0
                }
                goodsMapper.addSku(sku);
            });
        }

        return b;
    }

    @Override
    public PageResult<GoodsVo> getGoodsAll(GoodsDto goodsDto) {
        PageHelper.startPage(goodsDto.getPage(), goodsDto.getPageSize());
        List<GoodsVo> goodsVos = goodsMapper.getGoodsAll(goodsDto);
        Page<GoodsVo> page = (Page<GoodsVo>) goodsVos;
        return new PageResult<>(page.getTotal(), page.getResult());
    }

    @Override
    public List<SKU> getAllSku() {
        return goodsMapper.getAllSku();
    }

    // 新增方法实现
    @Override
    public List<GoodsVo> getAllGoodsWithCategory() {
        // 使用已有的 getGoodsAll 方法，传入空的 GoodsDto 来获取所有商品
        GoodsDto goodsDto = new GoodsDto();
        // 设置分页参数为较大的值以获取所有数据
        goodsDto.setPageSize(10000);
        List<GoodsVo> goodsVos = goodsMapper.getGoodsAll(goodsDto);
        return goodsVos;
    }
}